<template>
  <section class="component expression-base">
    <p v-if="preView" v-html="preViewExpressionStr"></p>
    <data-box class="expression-base-data-box" :data="expressionDataSet">
      <template slot="columns">
        <el-table-column label="链接关系" prop="relation">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.relation" @change="sendData" clearable>
              <el-option v-for="{name,value} of getRelationOptions(scope.$index)" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="左括号" prop="leftBracket">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.leftBracket" placeholder="可空置" @change="sendData" clearable>
              <el-option v-for="{name,value} of bracket.left" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="字段" prop="variable">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.variable" placeholder="请选择字段" @change="onVariableChange(scope.row)" clearable>
              <el-option v-for="{name,field} of fieldDataSet" :key="field" :label="name" :value="field"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作符" prop="symbol">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.symbol" placeholder="请选择操作符" @change="sendData" clearable>
              <el-option v-for="{name,value} of getSymbolOptions(scope.row.variable)" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="期望值" prop="value">
          <template slot-scope="scope">
            <el-select :disabled='openData===3||disabledData' v-model="scope.row.value" v-if="scope.row.operateType === 'SELECT'" @change="sendData" clearable>
              <el-option v-for="{name,code} of getValueOptions(scope.row.variable)" :key="code" :label="name" :value="code"></el-option>
            </el-select>
            <el-cascader :disabled='openData===3||disabledData' v-model="scope.row.cascaderValue" v-else-if="scope.row.operateType === 'CASCADER'" @change="values => onCascaderChange(scope.row,values)" :options="getValueOptions(scope.row.variable)" change-on-select :show-all-levels="false" clearable></el-cascader>
            <el-date-picker :disabled='openData===3||disabledData' type="date" v-model="scope.row.value" v-else-if="scope.row.operateType === 'DATEPICKER'" value-format="yyyy-MM-dd" @change="sendData" clearable></el-date-picker>
            <el-input v-model="scope.row.value" v-else placeholder="请输入期望值" @change="sendData" clearable :disabled='openData===3||disabledData'></el-input>
          </template>
        </el-table-column>
        <el-table-column label="右括号" prop="rightBracket">
          <template slot-scope="scope">
            <el-select v-model="scope.row.rightBracket" placeholder="可空置" @change="sendData" clearable :disabled='openData===3||disabledData'>
              <el-option v-for="{name,value} of bracket.right" :key="value" :label="name" :value="value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120px" v-if="(!disabledData&&show)||openData===1||(openData===2&&modifyData==='READY')||val==='READY'&&!show">
          <!-- <template slot="header">
            <a @click="preView = !preView">
              <i v-show="preView" class="el-icon-view"></i> {{`${preView ? '关闭':'打开'}预览`}}
            </a>
          </template> -->
          <template slot-scope="scope">
            <el-button type="text" v-show="(!disabledData)&&(openData!==3)" @click="deleteClick(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </template>
    </data-box>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Model } from "vue-property-decorator";
import { Form } from "element-ui";
import { operates, links, IstrategyInfo } from "./strategy-helper.config";
import DataBox from "~/components/common/data-box.vue";
import { StrategyConfigService } from "~/services/dataimp-service/strategy-config.service";
import { LabelingStrategyService } from "~/services/dataimp-service/labeling-strategy-service";
import { DictService } from "~/utils/dict.service";
import { CityService } from "~/utils/city.service"
import SvgIcon from "~/components/common/svg-icon.vue"

@Component({
  components: {
    
    SvgIcon
  }
})
export default class ExpressionBase extends Vue {
  @Dependencies(StrategyConfigService) private strategyConfigService: StrategyConfigService;

  @Dependencies(LabelingStrategyService) private labelingStrategyService: LabelingStrategyService;

  @Model("expressin-change")
  private expressionDataSet: IstrategyInfo[];

  @Prop({
    type:Number
  })
  private openData:number
  @Prop({type:String}) private modifyData
  @Prop({type:Boolean}) private disabledData:boolean
  @Prop({
    type:Boolean
  }) 
  private flag: boolean
  @Prop({type:String}) private val:string
  @Prop({type:Boolean}) private show:boolean
  
  private bracket = links.bracket;
  private fieldDataSet: any[] = []
  private preView = false;

  @Emit("expressin-change")
  private emitExpressionDataSet(data) {}

  private deleteClick(index) {
    this.expressionDataSet.splice(index, 1)
    if(index === 0){
      this.expressionDataSet[index].relation = " "
    }
    this.sendData()
  }

  private sendData() {
    this.emitExpressionDataSet(this.expressionDataSet.map(v => ({ ...v })))
  }

  /**
   * 新增行的时候判断 连接符是什么
   */
  private getRelationOptions(index: number) {
    return index === 0 ? links.relation.first : links.relation.normal
  }

  private get preViewExpressionStr() {
    let str = ""
    str = this.expressionDataSet.map((v: IstrategyInfo) => {
      return [v.relation, v.leftBracket, v.variable, v.symbol, v.value, v.rightBracket].join(' ')
    }).join(' ')
    return str
  }

  /**
   * 字段值变化，其他的数据需要清空重新设置
   */
  private onVariableChange(row: IstrategyInfo, index) {
    row.symbol = ""
    row.value = ''
    if (row.cascaderValue) row.cascaderValue = []
    row.operateType = this.valueOperateType(row.variable)
    this.sendData()
  }

  private onCascaderChange(row: IstrategyInfo, values: string[]) {
    row.value = values.length ? values[values.length - 1] : ''
    this.sendData()
  }


  /**
   * 根据字段获取需要的操作符
   */
  private getSymbolOptions(field: string) {
    const fieldConfig = this.fieldDataSet.find(x => x.field === field)
    return fieldConfig ? operates.filter(x => x.enable.includes(fieldConfig.symbol)) : []
  }

  /**
   * 获取操作类型
   */
  private valueOperateType(field: string) {
    const fieldConfig = this.fieldDataSet.find(x => x.field === field)
    if (!fieldConfig) return ''
    let type = "INPUT"
    switch (fieldConfig.source) {
      case "DICT":
      case "DATA":
        type = "SELECT"
        break;
      case "OTHER":
        type = this.getOtherType(fieldConfig.key)
        break;
      default:
        break;
    }
    return type
  }

  /**
   * 其他数据的数据类型
   */
  private getOtherType(key) {
    let type = "INPUT"
    switch (key) {
      case 'CITY':
        type = "CASCADER"
        break;
      case 'DATE':
        type = "DATEPTCKER"
        break;
      default:
        break;
    }
    return type
  }

  /**
   * 获取值选择数据源
   */
  private getValueOptions(field: string) {
    const fieldConfig = this.fieldDataSet.find(x => x.field === field)
    const source: any = []
    if (!fieldConfig) return []
    if (fieldConfig.source === "DICT") {
      // 如果是数据字典，则获取数据字典数据作为期望值的数据源
      return DictService.getDictData(fieldConfig.key)
    } else if (fieldConfig.source === "DATA") {
      return fieldConfig.dataList
    } else {
      return this.getLocalData(fieldConfig.key)
    }
  }

  /**
   * 获取值选择数据源-- 本地数据源
   */
  private getLocalData(type: string) {
    let data: any = []
    switch (type) {
      case "CITY":
        data = CityService.getCityData({ level: 2 })
        break;
      default:
        break;
    }
    return data
  }

  private mounted() {
    // 加载支持的字段和关联数据
    if(this.flag){
      this.labelingStrategyService.getLabelFields().subscribe(data => this.fieldDataSet = data)
    }else{
      this.strategyConfigService.getLabelNameFields().subscribe(data => this.fieldDataSet = data)
    }
  }


}
</script>

<style lang="less" scoped>
.component.expression-base {
  .expression-base-data-box {
    padding: 0;
  }
}
</style>
